/* eslint-disable prefer-regex-literals */
const express = require('express')
const router = express.Router()
const mysql = require('../util/mysql')
// const JWT = require('../util/jwt')
const multiparty = require('multiparty')

let Url = ''

// 跳转后从数据库里拿数据
router.get('/', async (req, res, next) => {
  const token = req.query.token
  const promisePool = mysql.sql()
  const info = await promisePool.query('select name,password,date,pho from user where token=?', [token])
  res.send({ code: 1, msg: info[0] })
})

// 头像上传
router.post('/upload', (req, res, next) => {
  const form = new multiparty.Form()
  form.uploadDir = './public/images'// 图片存储地址
  // form.keepExtensions=true;   //是否保留后缀
  form.parse(req, function (err, fields, files) { // 其中fields表示你提交的表单数据对象，files表示你提交的文件对象
    // console.log(fields, files)
    const url = files.file[0].path.replace(/\\/g, '/').replace(RegExp('public'), '')// 这个是对图片地址格式做一个格式修改
    Url = url
    if (err) {
      res.json({
        code: 400,
        msg: '上传失败！' + err
      })
    } else {
      res.send({
        code: 400,
        msg: '上传成功！',
        imgSrc: 'http://localhost:3000/' + url // 返回前台图片的地址（如果要在另一个系统中展示图片）
      })
    }
  })
})

// 修改用户数据
router.post('/updata', async (req, res, next) => {
  console.log(Url)
  const { name, password, birthday } = req.body.msg
  const { token } = req.body.msg1
  date = birthday.split('T')
  const promisePool = mysql.sql()
  await promisePool.query('update user set name=?,password=?,pho=?,date=? where token=?', [name, password, Url, date[0], token])
  // const info = await promisePool.query('select name,password,date,pho from user where token=?', [token])
  // console.log(info[0][0])
  res.send({ code: 1 })
})

// 我的评论
router.get('/show', async (req, res, next) => {
  const token = req.query.token
  const promisePool = mysql.sql()
  const info = await promisePool.query(`select info,header,time from user join message on user.uid=message.uid join art on message.uid=art.uid
  where token=?`, [token])
  res.send({ code: 1, info: info[0] })
})

module.exports = router
